package service

import (
	"context"
	"time"

	"gitee.com/jiebaiyou/formflow/internal/tokenutil"
	"gitee.com/jiebaiyou/formflow/model"
)

// signupService 实现了model.SignupService接口, 提供用户注册相关的业务逻辑
type signupService struct {
	userRepository model.UserRepository
	contextTimeout time.Duration
}

// NewSignupService 创建并返回一个实现了model.SignupService接口的实例
func NewSignupService(userRepository model.UserRepository, timeout time.Duration) model.SignupService {
	return &signupService{
		userRepository: userRepository,
		contextTimeout: timeout,
	}
}

// Create 创建新用户
func (su *signupService) Create(c context.Context, user *model.User) error {
	ctx, cancel := context.WithTimeout(c, su.contextTimeout)
	defer cancel()
	return su.userRepository.Create(ctx, user)
}

// GetUserByEmail 根据邮箱地址查询用户信息
func (su *signupService) GetUserByEmail(c context.Context, email string) (model.User, error) {
	ctx, cancel := context.WithTimeout(c, su.contextTimeout)
	defer cancel()
	return su.userRepository.GetByEmail(ctx, email)
}

// CreateAccessToken 为用户创建访问令牌(JWT)
func (su *signupService) CreateAccessToken(user *model.User, secret string, expiry int) (accessToken string, err error) {
	return tokenutil.CreateAccessToken(user, secret, expiry)
}

// CreateRefreshToken 为用户创建刷新令牌(JWT)
func (su *signupService) CreateRefreshToken(user *model.User, secret string, expiry int) (refreshToken string, err error) {
	return tokenutil.CreateRefreshToken(user, secret, expiry)
}
